<template>
    <div class="container">
        <div class="heade">
            <div class="header">
                <span class="text">基本信息</span>
            </div>
            <div class="heade-text">
                <el-form ref="form" :model="orderForm" label-width="80px" class="heade-form">
                    <el-form-item label="订单类型:">
                        <el-select v-model="orderForm.orderType" placeholder="请选择订单类型" style="width: 160px;">
                            <el-option label="普通订单" value="普通订单"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="客户名称">
                        <el-select v-model="orderForm.customerName" placeholder="请选择客户名称" style="width: 160px;">
                            <el-option label="客户A" value="客户A"></el-option>
                            <el-option label="客户B" value="客户B"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="客户类型">
                        <el-input v-model="orderForm.customerType" style="width: 160px;"></el-input>
                    </el-form-item>
                    <el-form-item label="业务员">
                        <el-select v-model="orderForm.employee" placeholder="请选择业务员" style="width: 160px;">
                            <el-option label="A员工" value="A员工"></el-option>
                            <el-option label="B员工" value="B员工"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="出货仓库">
                        <el-select v-model="orderForm.warehouse" placeholder="请选择出货仓库" style="width: 160px;">
                            <el-option label="A仓库" value="A仓库"></el-option>
                            <el-option label="B仓库" value="B仓库"></el-option>
                            <el-option label="C仓库" value="C仓库"></el-option>
                            <el-option label="D仓库" value="D仓库"></el-option>
                        </el-select>
                    </el-form-item>
                    <br />
                    <el-form-item label="发货日期">
                        <el-col :span="11">
                            <el-date-picker type="date" placeholder="选择日期" v-model="orderForm.deliveryDate"
                                style="width: 160px;"></el-date-picker>
                        </el-col>
                    </el-form-item>
                    <el-form-item label="销售类型">
                        <el-select v-model="orderForm.salesType" placeholder="请选择销售类型" style="width: 160px;">
                            <el-option label="车销" value="车销"></el-option>
                            <el-option label="访销" value="访销"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="配送车辆">
                        <el-select v-model="orderForm.vehicle" placeholder="请选择销售类型" style="width: 160px;">
                            <el-option label="A车" value="A车"></el-option>
                            <el-option label="B车" value="B车"></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
            </div>
        </div>
        <div class="between">
            <div class="header">
                <span class="text">选择商品</span>
            </div>
            <div class="heade-text">
                <el-form ref="form" :model="searchGoodsForm" label-width="80px" class="heade-select">
                    <el-form-item label="输入品牌">
                        <el-input v-model="searchGoodsForm.brand" style="width: 160px;"></el-input>
                    </el-form-item>
                    <el-form-item label="选择分类">
                        <el-input v-model="searchGoodsForm.goodsType" style="width: 160px;"></el-input>
                    </el-form-item>
                    <el-form-item label="商品标题">
                        <el-input v-model="searchGoodsForm.name" style="width: 160px;"></el-input>
                    </el-form-item>
                    <el-button style="width: 160px; height: 40px;" @click="searchGoods">搜索</el-button>
                    <el-button style="width: 160px; height: 40px;" @click="resetGoodsForm">重置</el-button>
                </el-form>
                <div class="result">
                    <div class="header">
                        <span class="text">搜索结果</span>
                        <el-button style="float: right; margin-right: 20px; font-size: 14px; margin-top: 6px;"
                            @click="dialogVisible = true">查看已添加商品</el-button>
                        <el-dialog title="商品明细" :visible.sync="dialogVisible" width="90%">
                            <div class="header">
                                <span class="text">
                                    商品明细
                                </span>
                                <span style="float: left; margin-left: 120px;">商品共:</span>
                                <span style="float: left; margin-left: 10px; color: red;">{{ goodsNum }}</span>
                                <span style="float: left; margin-left: 20px;">金额合计:</span>
                                <span style="float: left; margin-left: 10px; color: red;">{{ orderForm.total }}元</span>
                            </div>
                            <div class="between-table">
                                <el-table :header-cell-style="{ fontSize: '14px', textAlign: 'center' }"
                                    :cell-style="{ fontSize: '12px', textAlign: 'center' }"
                                    :row-class-name="'fixed-row-height'" ref="multipleTable" :data="chooseGoods" border
                                    tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange">
                                    <el-table-column label="商品名称" width="160">
                                        <template slot-scope="scope">{{ scope.row.name }}</template>
                                    </el-table-column>
                                    <el-table-column prop="luSupplyPrice" label="大单位/价格/比率" width="160">
                                        <template slot-scope="scope">
                                            <span>{{ scope.row.luSupplyPrice }}/{{ scope.row.lunit }} *{{ scope.row.conversionRatio }}</span>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="数量" width="160" align="center">
                                        <template slot-scope="scope">
                                            <el-input-number v-model="scope.row.num1" :min="0" :max="scope.row.lnum"
                                                size="small" @change="changeNum(scope.$index)">
                                            </el-input-number>
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="suSupplyPrice" label="小单位/价格">
                                        <template slot-scope="scope">
                                            <span>{{ scope.row.suSupplyPrice }}/{{ scope.row.sunit }}</span>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="数量" width="160" align="center">
                                        <template slot-scope="scope">
                                            <el-input-number v-model="scope.row.num2" :min="1" :max="scope.row.snum"
                                                size="small" @change="changeNum(scope.$index)">
                                            </el-input-number>
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="total" label="金额(元)"></el-table-column>
                                    <el-table-column label="商品类型" width="160">
                                        <template slot-scope="scope">
                                            <el-select v-model="scope.row.goodType" placeholder="商品类型" @change="changeType(scope.$index)">
                                                <el-option label="正常" value="正常"></el-option>
                                                <el-option label="赠品" value="赠品"></el-option>
                                            </el-select>
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="option" label="操作">
                                        <template slot-scope="scope">
                                            <el-button type="danger" icon="el-icon-delete" size="small"
                                                @click="deleteGood(scope.$index)"></el-button>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </div>
                            <div class="footer">
                                <div class="header">
                                    <span class="text">付款信息</span>
                                </div>
                                <div class="heade-text">
                                    <el-form ref="form" label-width="100px" class="heade-form">
                                        <el-form-item label="付款类型:" class="head-br">
                                            <el-select v-model="orderForm.paymentType" placeholder="请选择支付类型"
                                                style="width: 160px;">
                                                <el-option label="现金" value="现金"></el-option>
                                                <el-option label="支付宝" value="支付宝"></el-option>
                                                <el-option label="微信" value="微信"></el-option>
                                            </el-select>
                                        </el-form-item>
                                        <el-form-item label="优惠金额:" class="head-br">
                                            <el-input v-model="orderForm.discountAmount" placeholder="请输入优惠金额" @change="changeDiscount"
                                                style="width: 160px;"></el-input>
                                        </el-form-item>
                                        <el-form-item label="应付款金额:" class="head-br">
                                            <template slot-scope="scope">
                                                <span style="color: red;">
                                                    {{ orderForm.total }}
                                                </span>
                                                元
                                            </template>
                                        </el-form-item>
                                    </el-form>
                                </div>
                            </div>
                            <span slot="footer" class="dialog-footer">
                                <el-button type="success" style="width: 100px; height: 40px; font-size: 14px;" @click="submitOrder">
                                    提交
                                </el-button>
                                <el-button type="info" style="width: 100px; height: 40px; font-size: 14px;"
                                    @click="dialogVisible = false">取 消
                                </el-button>
                            </span>
                        </el-dialog>
                    </div>
                    <div class="between-table">
                        <el-table :header-cell-style="{ fontSize: '14px', textAlign: 'center' }" v-loading="loading"
                            :cell-style="{ fontSize: '12px', textAlign: 'center' }" ref="multipleTable" :data="GoodsList"
                            border tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange">
                            <el-table-column label="商品名称" width="160">
                                <template slot-scope="scope">{{ scope.row.name }}</template>
                            </el-table-column>
                            <el-table-column prop="lunit" label="大单位" width="160"></el-table-column>
                            <el-table-column prop="luSupplyPrice" label="大单位单价"></el-table-column>
                            <el-table-column prop="sunit" label="小单位"></el-table-column>
                            <el-table-column prop="suSupplyPrice" label="小单位价格" width="160"></el-table-column>
                            <el-table-column prop="number" label="现有库存(小单位)"></el-table-column>
                            <el-table-column prop="option" label="操作">
                                <template slot-scope="scope">
                                    <el-button :class="chooseGoods.some(item => item.id === scope.row.id) ? 'addButton' : 'column'"
                                        @click="addGood(scope)"
                                        :disabled="chooseGoods.some(item => item.id === scope.row.id)">
                                        {{ chooseGoods.some(item => item.id === scope.row.id) ? '已添加' : '添加' }}
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                        <div class="block">
                            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                                :page-size="pageSize" layout="prev, pager, next, jumper" :total="GoodsListCopy2.length">
                            </el-pagination>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
import { getGoodsList } from '@/api/goods.js'
import { addSalesOrders } from '@/api/sales_orders.js'
export default {
    data() {
        return {
            dialogVisible: false,
            orderForm: {
                id: 0,
                orderType: '普通订单',
                customerName: '',
                customerType: '',
                employee: '',
                warehouse: '',
                deliveryDate: '',
                salesType: '',
                vehicle: '',
                paymentType: '',
                discountAmount: 0,
                total: 0,
            },
            searchGoodsForm: {
                brand: '',
                goodsType: '',
                name: '',
            },
            goodsNum: 0,
            loading: true,
            pageSize: 6,
            GoodsList: [],
            GoodsListCopy: [],
            GoodsListCopy2: [],
            chooseGoods: [],
            multipleSelection: [],
        }
    },
    created() {
        this.getGoodsList();
    },
    methods: {
        submitOrder() {
            if (this.orderForm.customerName === '' || this.orderForm.customerType === '' || this.orderForm.employee === '' || this.orderForm.warehouse === '' || this.orderForm.deliveryDate === '' || this.orderForm.salesType === '' || this.orderForm.vehicle === '' || this.orderForm.paymentType === '') {
                this.$message({
                    message: '请填写完整信息',
                    type: 'warning'
                })
                return;
            }
            this.orderForm.deliveryDate = this.dateFormatByEl(this.orderForm.deliveryDate.toLocaleString().split('/').join('-'))
            // console.log(this.orderForm);
            const chooseGoodsForm = this.chooseGoods.map(item => {
                return {
                    id: item.id,
                    name: item.name,
                    count: item.numAll,
                    price: item.total,
                    num1: item.num1,
                    num2: item.num2,
                    goodType: item.goodType,
                }
            })
            // chooseGoodsForm转为json字符串
            // chooseGoodsForm = JSON.stringify(chooseGoodsForm)
            // console.log(JSON.stringify(chooseGoodsForm));
            addSalesOrders(this.orderForm, JSON.stringify(chooseGoodsForm)).then(res => {
                console.log(res);
                if (res.data.data === "添加销售订单成功") {
                    this.$message({
                        message: '提交成功',
                        type: 'success'
                    })
                    this.dialogVisible = false;
                    this.orderForm = {
                        orderType: '普通订单',
                        customerName: '',
                        customerType: '',
                        employee: '',
                        warehouse: '',
                        deliveryDate: '',
                        salesType: '',
                        vehicle: '',
                        paymentType: '',
                        discountAmount: 0,
                        total: 0,
                    }
                    this.goodsNum = 0;
                    this.chooseGoods = [];
                    this.getGoodsList();
                } else {
                    this.$message({
                        message: res.data.message,
                        type: 'error'
                    })
                }
            })
            this.dialogVisible = false;
        },
        dateFormatByEl(date) {
            // date = 2023-7-8 00:00:00月和日小于10的时候，前面加0
            var date1 = date.split(' ')[0].split('-')
            var date2 = date.split(' ')[1]
            var month = date1[1] < 10 ? '0' + date1[1] : date1[1]
            var day = date1[2] < 10 ? '0' + date1[2] : date1[2]
            date = date1[0] + '-' + month + '-' + day + ' ' + date2
            return date
        },
        addGood(scope) {
            // console.log(scope);
            // this.dialogVisible = true;
            // this.chooseGoods里加入num1,num2
            this.chooseGoods.push(
                {
                    id: scope.row.id,
                    name: scope.row.name,
                    lunit: scope.row.lunit,
                    luSupplyPrice: scope.row.luSupplyPrice,
                    sunit: scope.row.sunit,
                    suSupplyPrice: scope.row.suSupplyPrice,
                    conversionRatio: scope.row.conversionRatio,
                    number: scope.row.number,
                    num1: 0,
                    lnum: scope.row.number / scope.row.conversionRatio,
                    num2: 1,
                    snum: scope.row.number / 1,
                    total: scope.row.suSupplyPrice * 1 + scope.row.luSupplyPrice * 0,
                    goodType: '正常',
                    numAll: 1,
                }
            );
            let { goodsNum, orderTotal } = this.chooseGoods.reduce((total, item) => {
                return {
                    goodsNum: total.goodsNum + item.numAll,
                    orderTotal: total.orderTotal + item.total,
                }
            }, { goodsNum: 0, orderTotal: 0 });
            this.goodsNum = goodsNum;
            this.orderForm.total = orderTotal;
            // 判断库存
            // console.log(this.chooseGoods);
            this.$message({
                message: '添加成功',
                type: 'success'
            });
        },
        changeDiscount() {
            // console.log(this.orderForm.discountAmount);
            // 不允许输入负数
            if (this.orderForm.discountAmount < 0) {
                this.orderForm.discountAmount = 0;
                this.$message({
                    message: '折扣金额不能为负数',
                    type: 'warning'
                });
            }
            // 折扣金额不能大于订单总金额
            if (this.orderForm.discountAmount > this.orderForm.total) {
                this.orderForm.discountAmount = this.orderForm.total;
                this.$message({
                    message: '折扣金额不能大于订单总金额',
                    type: 'warning'
                });
            }
            this.orderForm.total = this.chooseGoods.reduce((total, item) => {
                return total + item.total;
            }, 0) - this.orderForm.discountAmount;
        },
        setNumAndTotal(){
            let { goodsNum, orderTotal } = this.chooseGoods.reduce((total, item) => {
                return {
                    goodsNum: total.goodsNum + item.numAll,
                    orderTotal: total.orderTotal + item.total,
                }
            }, { goodsNum: 0, orderTotal: 0 });
            this.goodsNum = goodsNum;
            if (this.orderForm.discountAmount > orderTotal) {
                this.orderForm.discountAmount = orderTotal;
                this.$message({
                    message: '折扣金额不能大于订单总金额',
                    type: 'warning'
                });
            }
            this.orderForm.total = orderTotal - this.orderForm.discountAmount;
        },
        changeType(index) {
            // 正常和赠送
            // console.log(index);
            // console.log(this.chooseGoods[index].goodType);
            if (this.chooseGoods[index].goodType === '正常') {
                this.chooseGoods[index].total = this.chooseGoods[index].suSupplyPrice * this.chooseGoods[index].num2 + this.chooseGoods[index].luSupplyPrice * this.chooseGoods[index].num1;
            } else {
                this.chooseGoods[index].total = 0;
            }
            this.setNumAndTotal();
        },
        changeNum(index) {
            let numAll1 = this.chooseGoods[index].num1 * this.chooseGoods[index].conversionRatio + this.chooseGoods[index].num2;
            //判断库存（lnum和snum分别是大单位和小单位的选择max）
            if (numAll1 > this.chooseGoods[index].number && this.chooseGoods[index].number - this.chooseGoods[index].numAll > this.chooseGoods[index].conversionRatio) {
                this.$message({
                    message: '库存不足,已经为您分配了大单位最大库存',
                    type: 'warning'
                });
                this.chooseGoods[index].lnum = parseInt(this.chooseGoods[index].number / this.chooseGoods[index].conversionRatio);
                this.chooseGoods[index].num1 = this.chooseGoods[index].lnum;
                // return;
                // this.chooseGoods[index].snum = this.chooseGoods[index].num2 - 1;
            }
            else if (numAll1 > this.chooseGoods[index].number && this.chooseGoods[index].number - this.chooseGoods[index].numAll < this.chooseGoods[index].conversionRatio) {
                this.$message({
                    message: '已经为您减少了对应的小单位数量',
                    type: 'success'
                });
                this.chooseGoods[index].snum = this.chooseGoods[index].number - this.chooseGoods[index].num1 * this.chooseGoods[index].conversionRatio;
                this.chooseGoods[index].num2 = this.chooseGoods[index].snum;
            }
            this.chooseGoods[index].numAll = this.chooseGoods[index].num1 * this.chooseGoods[index].conversionRatio + this.chooseGoods[index].num2;
            if (this.chooseGoods[index].goodType === '正常') {
                this.chooseGoods[index].total = this.chooseGoods[index].num1 * this.chooseGoods[index].luSupplyPrice + this.chooseGoods[index].num2 * this.chooseGoods[index].suSupplyPrice;
            } else {
                this.chooseGoods[index].total = 0;
            }
            this.setNumAndTotal();
            this.chooseGoods[index].lnum = parseInt(this.chooseGoods[index].number / this.chooseGoods[index].conversionRatio);
            this.chooseGoods[index].snum = this.chooseGoods[index].number - this.chooseGoods[index].num1 * this.chooseGoods[index].conversionRatio;
        },
        deleteGood(index) {
            this.$confirm('确定删除该商品吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.chooseGoods.splice(index, 1);
                this.setNumAndTotal();
                this.$message({
                    message: '删除成功',
                    type: 'success'
                });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        getGoodsList() {
            getGoodsList().then(res => {
                // console.log(res);
                this.GoodsListCopy = res.data.data;
                this.GoodsListCopy2 = res.data.data;
                this.GoodsList = this.GoodsListCopy2.slice(0, this.pageSize);
                this.loading = false;
            })
        },
        searchGoods() {
            // console.log(this.searchGoodsForm);
            // 从GoodsListCopy中筛选
            let { name, goodsType, brand } = this.searchGoodsForm;
            this.GoodsListCopy2 = this.GoodsListCopy.filter(item => {
                return item.name.indexOf(name) !== -1 && item.goodsType.indexOf(goodsType) !== -1 && item.brand.indexOf(brand) !== -1;
            });
            this.GoodsList = this.GoodsListCopy2.slice(0, this.pageSize);
        },
        resetGoodsForm() {
            this.searchGoodsForm = {
                name: '',
                goodsType: '',
                brand: '',
            }
            this.GoodsListCopy2 = this.GoodsListCopy;
            this.GoodsList = this.GoodsListCopy2.slice(0, this.pageSize);
        },
        handleSizeChange(val) {
            console.log(`每页 ${val} 条`);
        },
        handleCurrentChange(val) {
            this.GoodsList = this.GoodsListCopy2.slice((val - 1) * this.pageSize, val * this.pageSize);
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
        }
    }
}

</script>

<style>
.heade-text {
    border: 1px solid rgba(228, 228, 228, 1);
    text-align: center;
}

.heade-form {
    display: flex;
    flex-wrap: wrap;
    position: relative;
    top: 12px;
}

.heade-form .el-form-item {
    margin-right: 20px;
}

.heade-select {
    display: flex;
    position: relative;
    flex-wrap: wrap;
    top: 25px;
}

.heade-select .el-form-item {
    margin-right: 20px;
}

.head-br {
    display: block;
}

.block {
    margin-top: 20px;
}

.text {
    font-size: 14px;
    position: absolute;
    left: 12px;
}

.info1 {
    font-size: 14px;
    position: absolute;
    right: 70px;
    top: 14px;
}

.info {
    font-size: 14px;
    position: absolute;
    right: 12px;
    top: 14px;
}

.header {
    position: relative;
    height: 50px;
    line-height: 50px;
    text-align: center;
    background-color: rgba(243, 243, 243, 1);
    border: 1px solid rgba(228, 228, 228, 1);
}

.add {
    cursor: pointer;
    font-size: 14px !important;
}

.add:hover {
    color: #409EFF;
    text-decoration: underline;
}

.between .header {
    margin-top: 20px;
}

.column {
    font-size: 14px;
    margin-right: 5px;
}

.result {
    padding: 15px;
}

.end span {
    font-size: 14px;
    margin: 10px;
}

.fixed-row-height {
    height: 50px;
}

/* addButton的伪类以抛物线的形式动画移动到右下角 */
/* .addButton::before {
    content: '';
    position: absolute;
    left: 70px;
    top: 0px;
    z-index: 999999;
    width: 20px;
    height: 20px;
    border-radius: 50%;
    background-color: #409EFF;
    animation: moveY 2s cubic-bezier(0.5, -1, 1, 1) forwards;
}
@keyframes moveY {
    to {
        transform: translateY(300px);
    }
} */
/* 伪类结束 */

</style>